$(function () {
    $('#link_reg,#link_login').click(function () {
        $(this).parents('form').hide().siblings('form').show();
    })

    // $('#link_login').click(function () {
    //     $(this).parents('form').hide().siblings('form').show();
    // })
    // 自定义校验规则
    layui.form.verify({
        pwd: [/^\S{6,12}$/, '密码不能有空格,并且是6到12位'],
        repwd: function (value) {
            var pwds = $('#reg_form [name="password"]').val();
            if (pwds != value) {
                return "密码不一致"
            }
            // console.log(pwds, value)
        }
    })

    // 注册功能
    var layer = layui.layer
    $('#reg_form').on('submit', function (e) {
        e.preventDefault();
        var username = $('#reg_form [name="username"]').val();
        var password = $('#reg_form [name="password"]').val();
        $.post('/api/reguser', { username: username, password: password }, function (res) {
            if (res.status != 0) { return layer.msg('注册失败') }
            layer.msg('注册成功 !请登录')
            // 注册成功后模拟人自动点击去登录事件
            $("#link_login").click();
        })
    })

    // 登录功能
    $('#login_form').on('submit', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'post',
            url: '/api/login',
            data: $('#login_form').serialize(),
            success: function (res) {
                if (res.status != 0) return layer.msg(res.message);
                layer.msg(res.message);
                localStorage.setItem('token', res.token);
                location.href = "/index.html"
            }
        })
    })
})